<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {onMounted, reactive, ref, watch} from "vue";
import {
  CalendarOutlined,
  EyeOutlined,
  FileSearchOutlined,
  FireOutlined,
  RightOutlined,
  SearchOutlined,
  TagOutlined,
} from "@ant-design/icons-vue";
import {categoryApi, postApi} from "@/api";
import dayjs from "dayjs";
import {filterHtmlTags, truncateString} from "@/utils";
import type {CategoryListVo} from "@/type";

const route = useRoute();
const router = useRouter();

const searchText = ref(route.query.k as string);
// const timeRange = ref("all");
// const categoryNameFilter = ref("all");
const params = reactive({
  page: 1,
  pageSize: 10,
  time: "",
  category: "",
  sort: "",
});
const total = ref(0);
watch(
    () => route.query.k,
    (newValue) => {
      searchText.value = newValue as string;
      search();
    },
);

// 搜索结果
const searchResults = ref<any[]>([]);
const category = ref<
    {
      id: number;
      name: string;
    }[]
>([]);
// 推荐文章
const recommendedArticles = ref([
  {
    id: 101,
    title: "TypeScript 与 JavaScript 协同开发实践",
    coverImage:
        "https://public.readdy.ai/ai/img_res/b9c312eae08b4bedc462b1652a01fab9.jpg",
    views: 2156,
  },
]);

// 高亮搜索关键词
const highlightKeyword = (text: string, keyword: string = "关键词") => {
  if (!keyword.trim()) return text;
  const regex = new RegExp(`(${keyword})`, "gi");
  return text.replace(regex, '<span class="bg-yellow-200">$1</span>');
};

// 分页变化
const onPageChange = (page: number) => {
  params.page = page;
  console.log("切换到页码:", page);
};
const handleViewDetails = (id: number, title: string) => {
  router.push({name: "blogItem", params: {id, title}});
};
const t = ref<number | string>(0);
const search = async () => {
  // 记录开始时间
  const startTime = Date.now();
  const res = await postApi.search({
    keyword: searchText.value,
    ...params,
  });
  // 计算耗时（毫秒）
  const elapsedMs = Date.now() - startTime;
  t.value = (elapsedMs / 1000).toFixed(2);
  total.value = res.count;
  searchResults.value = res.rows.map((item: any) => {
    return {
      ...item,
      createdAt: dayjs(String(item.createdAt)).format("YYYY-MM-DD"),
      excerpt: truncateString(filterHtmlTags(item.excerpt), 120),
    };
  });
};
// 获取分类
const getCategoryList = async () => {
  const res = await categoryApi.getCategoryList();
  category.value = res.result.map((item: CategoryListVo) => {
    return {
      id: item.id,
      name: item.name,
    };
  });
};
onMounted(() => {
  search();
  getCategoryList();
});
</script>

<template>
  <div class="min-h-screen">
    <!-- 搜索结果区域 -->
    <div class="pt-24 pb-8">
      <div class="max-w-7xl mx-auto px-4">
        <div class="bg-white rounded-lg shadow-sm p-6 mb-8">
          <div class="flex items-center mb-4">
            <search-outlined class="text-2xl mr-3 text-blue-500"/>
            <h1 class="text-2xl font-bold">
              搜索结果: "{{ searchText || "关键词" }}"
            </h1>
          </div>
          <p class="text-gray-600">
            找到 {{ searchResults.length }} 条相关结果，用时 {{ t }} 秒
          </p>
        </div>
        <!-- 搜索筛选区域 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div class="flex flex-wrap items-center justify-between gap-4">
            <div class="flex items-center space-x-4">
              <span class="text-gray-600">排序方式:</span>
              <a-select
                  v-model:value="params.sort"
                  style="width: 140px"
                  class="!rounded-button"
                  @change="search"
              >
                <a-select-option value="">常规</a-select-option>
                <a-select-option value="latest">最新发布</a-select-option>
                <a-select-option value="popular">最多阅读</a-select-option>
              </a-select>
            </div>
            <div class="flex items-center space-x-4">
              <span class="text-gray-600">文章分类:</span>
              <a-select
                  v-model:value="params.category"
                  style="width: 140px"
                  class="!rounded-button"
                  @change="search"
              >
                <a-select-option value="">全部分类</a-select-option>
                <a-select-option v-for="item in category" :value="item.id">{{
                    item.name
                  }}
                </a-select-option>
              </a-select>
            </div>
            <div class="flex items-center space-x-4">
              <span class="text-gray-600">时间范围:</span>
              <a-select
                  v-model:value="params.time"
                  style="width: 140px"
                  class="!rounded-button"
                  @change="search"
              >
                <a-select-option value="">全部时间</a-select-option>
                <a-select-option :value="7">最近一周</a-select-option>
                <a-select-option :value="30">最近一月</a-select-option>
                <a-select-option :value="365">最近一年</a-select-option>
              </a-select>
            </div>
          </div>
        </div>
        <!-- 搜索结果列表 -->
        <div class="space-y-6">
          <div
              v-for="result in searchResults"
              :key="result.id"
              class="bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow duration-300 overflow-hidden cursor-pointer"
          >
            <div class="flex flex-col md:flex-row">
              <div class="md:w-1/4 overflow-hidden">
                <img
                    :src="result.coverImage"
                    :alt="result.title"
                    class="w-full h-full object-coverImage object-top"
                />
              </div>
              <div class="p-6 md:w-3/4">
                <div class="flex items-center text-xs text-gray-500 mb-2">
                  <calendar-outlined class="mr-1"/>
                  <span>{{ result.createdAt }}</span>
                  <div class="mx-2 w-1 h-1 rounded-full bg-gray-300"></div>
                  <eye-outlined class="mr-1"/>
                  <span>{{ result.views }} 阅读</span>
                  <div class="mx-2 w-1 h-1 rounded-full bg-gray-300"></div>
                  <tag-outlined class="mr-1"/>
                  <span>{{ result.categoryName }}</span>
                </div>
                <h3 class="text-xl font-medium mb-3">
                  <span
                      v-html="highlightKeyword(result.title, searchText)"
                  ></span>
                </h3>
                <p class="text-gray-600 mb-4">
                  <span
                      v-html="highlightKeyword(result.excerpt, searchText)"
                  ></span>
                </p>
                <div class="flex justify-between items-center">
                  <div class="flex flex-wrap gap-2">
                    <span
                        v-for="(tag, index) in result.tags"
                        :key="index"
                        class="text-xs px-2 py-1 bg-gray-100 text-gray-600 rounded-full"
                    >
                      {{ tag }}
                    </span>
                  </div>
                  <a-button
                      type="primary"
                      size="small"
                      @click="handleViewDetails(result.id, result.title)"
                      class="!rounded-button whitespace-nowrap cursor-pointer"
                  >
                    查看详情
                    <template #icon>
                      <right-outlined/>
                    </template>
                  </a-button>
                </div>
              </div>
            </div>
          </div>
          <!-- 无搜索结果时显示 -->
          <div
              v-if="searchResults.length === 0"
              class="bg-white rounded-lg shadow-sm p-8 text-center"
          >
            <file-search-outlined class="text-5xl text-gray-300 mb-4"/>
            <h3 class="text-xl font-medium mb-2">未找到相关结果</h3>
            <p class="text-gray-600 mb-6">
              抱歉，没有找到与"{{
                searchText || "关键词"
              }}"相关的内容，请尝试其他关键词。
            </p>
            <div class="flex justify-center space-x-4">
              <a-button
                  class="!rounded-button whitespace-nowrap cursor-pointer"
              >
                返回首页
              </a-button>
              <a-button
                  type="primary"
                  class="!rounded-button whitespace-nowrap cursor-pointer"
              >
                浏览所有文章
              </a-button>
            </div>
          </div>
          <!-- 分页 -->
          <div class="mt-8 flex justify-center">
            <a-pagination
                v-model:current="params.page"
                :total="total"
                show-quick-jumper
                :page-size="params.pageSize"
                @change="onPageChange"
            />
          </div>
        </div>
        <!-- 相关推荐 -->
        <!--        <div class="mt-12 bg-white rounded-lg shadow-sm p-6">-->
        <!--          <h2 class="text-xl font-bold mb-6 flex items-center">-->
        <!--            <fire-outlined class="mr-2 text-orange-500" />-->
        <!--            您可能感兴趣的内容-->
        <!--          </h2>-->
        <!--          <div class="grid grid-cols-1 md:grid-cols-3 gap-6">-->
        <!--            <div-->
        <!--              v-for="(article, index) in recommendedArticles"-->
        <!--              :key="index"-->
        <!--              class="border rounded-lg hover:shadow-md transition-shadow duration-300 overflow-hidden cursor-pointer"-->
        <!--            >-->
        <!--              <div class="h-40 overflow-hidden">-->
        <!--                <img-->
        <!--                  :src="article.coverImage"-->
        <!--                  :alt="article.title"-->
        <!--                  class="w-full h-full object-coverImage"-->
        <!--                />-->
        <!--              </div>-->
        <!--              <div class="p-4">-->
        <!--                <h3 class="text-lg font-medium mb-2 line-clamp-2 h-14">-->
        <!--                  {{ article.title }}-->
        <!--                </h3>-->
        <!--                <div class="flex justify-between items-center">-->
        <!--                  <div class="text-xs text-gray-500">-->
        <!--                    <eye-outlined class="mr-1" />-->
        <!--                    <span>{{ article.views }} 阅读</span>-->
        <!--                  </div>-->
        <!--                  <a-button-->
        <!--                    type="link"-->
        <!--                    size="small"-->
        <!--                    class="!rounded-button whitespace-nowrap cursor-pointer p-0"-->
        <!--                  >-->
        <!--                    查看详情-->
        <!--                    <template #icon>-->
        <!--                      <right-outlined />-->
        <!--                    </template>-->
        <!--                  </a-button>-->
        <!--                </div>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </div>-->
      </div>
    </div>
  </div>
</template>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

:deep(.ant-input-search .ant-input) {
  border-radius: 8px;
}

:deep(.ant-btn-primary) {
  background-color: #1890ff;
}

:deep(.ant-input-group-addon) {
  background-color: transparent;
}

:deep(.ant-select-selector) {
  border-radius: 8px !important;
}

:deep(.ant-pagination-item-active) {
  border-color: #1890ff;
}

:deep(.ant-pagination-item-active a) {
  color: #1890ff;
}
</style>
